package com.cskaoyan.controller;

import com.cskaoyan.bean.User;
import com.cskaoyan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author stone
 * @date 2022/05/02 21:27
 */

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("register")
    public User register1(User user) {
        userService.add(user);
        return user;
    }

    @PostMapping("register")
    public User register2(@RequestBody User user) {
        userService.add(user);

        return user;
    }

    @RequestMapping("login")
    public String login(HttpSession session, String username, String password) {
        User user = userService.query(username, password);
        System.out.println("user =" + user);
        if (user != null) {
            session.setAttribute("user",user);
        }
        return "OK";
    }

    @RequestMapping("get")
    public User get(@SessionAttribute("user") User user) {
        if (user != null) {
            return user;
        }
        return null;
    }

    @RequestMapping("id/{id}")
    public User queryUserById(@PathVariable("id") Integer id) {
        return userService.queryByPrimaryKey(id);
    }

    //松哥  → 前端来处理 → URL编码的松哥
    //%E6%9D%BE%E5%93%A5 → 松哥
    @RequestMapping("cookie")
    public User cookie(@CookieValue("username") String username) {
        List<User> query = userService.query(username);
        return query.size() > 0 ? query.get(0) : null;
    }

}
